package com.briup.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Arrays;

public class BatchTest {
    public static void main(String[] args) throws Exception {
        // 批处理，一次性执行多个sql语句
        var driver =  "com.mysql.cj.jdbc.Driver";
        var url = "jdbc:mysql://192.168.179.11:3306/briup";
        var user = "root";
        var password = "root";
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, user, password);
        Statement st = conn.createStatement();
        // 准备多条sql语句
        String sql1 = "drop table t_user";
        String sql2 = """
                      create table t_user(
                        id int primary key,
                        name varchar(50) not null,
                        age int
                       )
                      """;
        String sql3 = "insert into t_user values (1,'tom',21)";
        String sql4 = "insert into t_user values (2,'jerry',23)";
        String sql5 = "insert into t_user values (3,'bob',20)";
        String sql6 = "update t_user set name='lilith' where id=3";
        // String sql7 = "select * from t_user";
        // 加入到批处理
        st.addBatch(sql1);
        st.addBatch(sql2);
        st.addBatch(sql3);
        st.addBatch(sql4);
        st.addBatch(sql5);
        st.addBatch(sql6);
        // st.addBatch(sql7);
        // 执行批处理
        int[] ints = st.executeBatch();
        // 输出结果
        System.out.println(Arrays.toString(ints));
        // 关闭资源
        st.cancel();
        conn.close();
    }
}
